مراحل زیر بهترتیب برای افزودن کامل Extractor پاورپوینت به پروژه xAiApi انجام میشود:
گام ۱ — افزودن بسته NuGet جدید
در فایل xAiApi.csproj، بسته زیر را در صورت عدم وجود اضافه کنید:
<PackageReference Include="NPOI" Version="2.7.1" />
💡 نکته: بسته DocumentFormat.OpenXml در حال حاضر برای پردازش `.docx` در پروژه وجود دارد و نیازی به افزودن مجدد نیست.
گام ۲ — ایجاد اینترفیس اختصاصی
فایل جدید Interfaces/Extractors/IXPowerPointFileContentExtractor.cs را با محتوای نشاندادهشده در بخش ۴ (بالا) ایجاد کنید.
گام ۳ — پیادهسازی کلاس اصلی
فایل Providers/Extractors/XPowerPointFileContentExtractor.cs را با ساختار زیر ایجاد کنید:
using System;
using System.IO;
using System.Linq;
using NPOI.HSLF.UserModel;
using System.Text;
using System.Threading;
using xAiModels.Models;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;
using xAiApi.Interfaces.Extractors;
using DrawingText = DocumentFormat.OpenXml.Drawing.Text;
namespace xAiApi.Providers.Extractors
{
/// <summary>
/// Extracts content from all PowerPoint formats
/// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot)
/// </summary>
public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor
{
private static readonly string[] SupportedMimeTypes =
[
// OpenXML Formats
"application/vnd.openxmlformats-officedocument.presentationml.presentation", // .pptx
"application/vnd.openxmlformats-officedocument.presentationml.slideshow", // .ppsx
"application/vnd.openxmlformats-officedocument.presentationml.template", // .potx
"application/vnd.ms-powerpoint.presentation.macroEnabled.12", // .pptm
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12", // .ppsm
"application/vnd.ms-powerpoint.template.macroEnabled.12", // .potm
// Legacy Binary Formats (.ppt / .pps / .pot share same MIME)
"application/vnd.ms-powerpoint"
];
public bool CanExtract(string mimeType)
{
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default)
{
var result = await ExtractRichAsync(
fileStream: fileStream,
fileName: "presentation",
mimeType: mimeType,
cancellationToken: cancellationToken
);
return result.Text;
}
public async Task<XFileExtractionResult> ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default)
{
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
try
{
if (IsOpenXmlFormat(mimeType))
{
result.Text = await ExtractOpenXmlAsync(
fileStream, cancellationToken);
}
else if (IsLegacyFormat(mimeType))
{
result.Text = await ExtractLegacyAsync(
fileStream, cancellationToken);
}
else
{
result.ErrorMessage =
$"Unsupported PowerPoint MIME type: {mimeType}";
}
}
catch (Exception ex)
{
result.ErrorMessage =
$"PowerPoint extraction failed: {ex.Message}";
}
return result;
}
private static bool IsOpenXmlFormat(string mimeType)
{
return mimeType?.ToLowerInvariant() switch
{
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => true,
"application/vnd.openxmlformats-officedocument.presentationml.slideshow" => true,
"application/vnd.openxmlformats-officedocument.presentationml.template" => true,
"application/vnd.ms-powerpoint.presentation.macroEnabled.12" => true,
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => true,
"application/vnd.ms-powerpoint.template.macroEnabled.12" => true,
_ => false
};
}
private static bool IsLegacyFormat(string mimeType)
{
return mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint";
}
}
}
گام ۴ — پیادهسازی متد ExtractOpenXmlAsync
این متد برای پردازش ۶ فرمت OpenXML استفاده میشود و از `DocumentFormat.OpenXml` بهره میبرد. متن اسلایدها، یادداشتهای سخنران، جداول و تصاویر را استخراج میکند:
private async Task<string> ExtractOpenXmlAsync(
Stream fileStream,
CancellationToken cancellationToken)
{
var sb = new StringBuilder();
// Copy to MemoryStream (OpenXml requires seekable stream)
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
using var presentationDocument = PresentationDocument.Open(ms, false);
var presentationPart = presentationDocument.PresentationPart;
if (presentationPart == null)
{
throw new InvalidDataException("Invalid OpenXML PowerPoint structure");
}
var slideParts = presentationPart.SlideParts.ToList();
var slideIndex = 0;
foreach (var slidePart in slideParts)
{
if (cancellationToken.IsCancellationRequested) break;
slideIndex++;
sb.AppendLine($"[Slide {slideIndex}]");
// 1. Extract slide title
var slideTitle = GetSlideTitle(slidePart);
if (!string.IsNullOrWhiteSpace(slideTitle))
{
sb.AppendLine($"Title: {slideTitle}");
}
// 2. Extract body texts
var bodyTexts = slidePart.Slide
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t) && t != slideTitle)
.ToList();
if (bodyTexts.Count > 0)
{
sb.AppendLine("Content:");
foreach (var text in bodyTexts)
{
sb.AppendLine($" - {text}");
}
}
// 3. Extract tables
var tables = ExtractOpenXmlTables(slidePart);
if (!string.IsNullOrWhiteSpace(tables))
{
sb.AppendLine("[Tables]");
sb.AppendLine(tables);
}
// 4. Extract speaker notes
var notes = GetSpeakerNotes(slidePart);
if (!string.IsNullOrWhiteSpace(notes))
{
sb.AppendLine("[Speaker Notes]");
sb.AppendLine(notes);
}
// 5. Image count metadata
var imageCount = slidePart.ImageParts?.Count() ?? 0;
if (imageCount > 0)
{
sb.AppendLine($"[Images: {imageCount}]");
}
sb.AppendLine();
}
return sb.ToString().TrimEnd();
}
گام ۵ — پیادهسازی متدهای کمکی OpenXML
private static string GetSlideTitle(SlidePart slidePart)
{
// Title placeholder has specific type
var titleShape = slidePart.Slide
.Descendants<DocumentFormat.OpenXml.Presentation.Shape>()
.FirstOrDefault(s => s.NonVisualShapeProperties?
.NonVisualDrawingProperties?
.Name?.Value?
.StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true);
if (titleShape != null)
{
var titleText = titleShape
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t));
return string.Join(" ", titleText);
}
return null;
}
private static string GetSpeakerNotes(SlidePart slidePart)
{
var notesSlidePart = slidePart.NotesSlidePart;
if (notesSlidePart?.NotesSlide == null)
{
return null;
}
var notesTexts = notesSlidePart.NotesSlide
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t))
.ToList();
return notesTexts.Count > 0
? string.Join(Environment.NewLine, notesTexts)
: null;
}
private static string ExtractOpenXmlTables(SlidePart slidePart)
{
var sb = new StringBuilder();
var tableElements = slidePart.Slide
.Descendants<DocumentFormat.OpenXml.Drawing.Table>();
var tableIndex = 0;
foreach (var table in tableElements)
{
tableIndex++;
sb.AppendLine($" Table {tableIndex}:");
foreach (var row in table
.Descendants<DocumentFormat.OpenXml.Drawing.TableRow>())
{
var cells = row
.Descendants<DocumentFormat.OpenXml.Drawing.TableCell>()
.Select(c => string.Join(" ", c
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t))))
.ToList();
if (cells.Count > 0)
{
sb.AppendLine($" | {string.Join(" | ", cells)} |");
}
}
sb.AppendLine();
}
return sb.ToString();
}
گام ۶ — پیادهسازی متد ExtractLegacyAsync
این متد برای پردازش `.ppt`، `.pps` و `.pot` استفاده میشود و از `NPOI.HSLF` بهره میبرد:
private async Task<string> ExtractLegacyAsync(
Stream fileStream,
CancellationToken cancellationToken)
{
var sb = new StringBuilder();
// HSLF requires seekable stream
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
using var hslfSlideShow = new HSLFSlideShow(ms);
var slides = hslfSlideShow.Slides.ToList();
var slideIndex = 0;
foreach (var slide in slides)
{
if (cancellationToken.IsCancellationRequested) break;
slideIndex++;
sb.AppendLine($"[Slide {slideIndex}]");
var textParts = new List<string>();
var imageCount = 0;
foreach (var shape in slide.Shapes)
{
if (shape is HSLFTextShape textShape)
{
if (!string.IsNullOrWhiteSpace(textShape.Text))
{
textParts.Add(textShape.Text.Trim());
}
}
else if (shape is HSLFPictureShape)
{
imageCount++;
}
}
if (textParts.Count > 0)
{
sb.AppendLine("Content:");
foreach (var text in textParts)
{
sb.AppendLine($" - {text}");
}
}
if (imageCount > 0)
{
sb.AppendLine($"[Images: {imageCount}]");
}
sb.AppendLine();
}
return sb.ToString().TrimEnd();
}
⚠ نکته مهم درباره NPOI.HSLF: کتابخانه HSLF در NPOI برای فرمتهای قدیمی `.ppt`، `.pps`، `.pot` طراحی شده و از استخراج یادداشتهای سخنران و جداول در این فرمتها بهطور کامل پشتیبانی نمیکند (به دلیل پیچیدگی ساختار Binary قدیمی مایکروسافت). برای این فرمتها، استخراج متن اصلی و شمارش تصاویر در اختیار شما قرار میگیرد.
گام ۷ — ثبت در Dependency Injection
در فایل Startup.cs، در متد `ConfigureServices`، خط زیر را به بخش ثبت Extractor ها اضافه کنید:
//
// Register File Content Extractors ...
services.AddSingleton<IXFileContentExtractorBase, XPdfFileContentExtractor>();
services.AddSingleton<IXFileContentExtractorBase, XDocxFileContentExtractor>();
services.AddSingleton<IXFileContentExtractorBase, XImageFileContentExtractor>();
services.AddSingleton<IXFileContentExtractorBase, XAudioFileContentExtractor>();
services.AddSingleton<IXFileContentExtractorBase, XExcelFileContentExtractor>();
services.AddSingleton<IXFileContentExtractorBase, XVisionFileContentExtractor>();
services.AddSingleton<IXFileContentExtractorBase, XPlainTextFileContentExtractor>();
services.AddSingleton<IXFileContentExtractorBase, XPowerPointFileContentExtractor>(); // ← جدید
✓ بدون نیاز به تغییرات دیگر: کلاس XFileContentExtractor (Composite Extractor) بهطور خودکار تمام پیادهسازیهای IXFileContentExtractorBase را دریافت و مدیریت میکند. بنابراین تنها ثبت در DI کافی است و نیازی به تغییر در منطق Composite Extractor نیست.
گام ۸ — تنظیمات اختیاری در appsettings.json
در صورت نیاز به کنترل رفتار استخراج، میتوانید بخش پیکربندی اختصاصی اضافه کنید (اختیاری، اما برای آینده توصیه میشود):
{
"AiApiConfiguration": {
"PowerPoint": {
"IncludeSpeakerNotes": true,
"IncludeTables": true,
"IncludeImageMetadata": true,
"MaxSlideCount": 0
}
}
}
💡 نکته: این تنظیمات برای فاز فعلی اختیاری هستند و در صورت عدم وجود، مقادیر پیشفرض (همه `true`، بدون محدودیت اسلاید) استفاده میشود. در فاز بعدی میتوان یک XPowerPointDescriptor مشابه XPDFToImageDescriptor اضافه کرد.